package com.sigmatrix.h5.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sigmatrix.h5.properties.RedissonProperties;
import com.sigmatrix.h5.redisson.DistributedLocker;
import com.sigmatrix.h5.redisson.DistributedObject;
import com.sigmatrix.h5.redisson.RedissonLocker;

/**
 * Redisson 配置类
 *
 */
@Configuration
@EnableConfigurationProperties(RedissonProperties.class)
public class RedissonAutoConfiguration {

	@Autowired
	private RedissonProperties redssionProperties;

	/**
	 * 哨兵模式
	 */
	// TODO RedissonClient shutdown
	@Bean
	@ConditionalOnProperty(name = "h5.redisson.master-name")
	public RedissonClient redissonSentinel() {
		Config config = new Config();
		SentinelServersConfig serverConfig = config.useSentinelServers()
				.addSentinelAddress(redssionProperties.getSentinelAddresses())
				.setMasterName(redssionProperties.getMasterName()).setTimeout(redssionProperties.getTimeout())
				.setMasterConnectionPoolSize(redssionProperties.getMasterConnectionPoolSize())
				.setSlaveConnectionPoolSize(redssionProperties.getSlaveConnectionPoolSize()).setDatabase(redssionProperties.getDatabase());

		if (redssionProperties.getPassword() != null && !"".equals(redssionProperties.getPassword())) {
			serverConfig.setPassword(redssionProperties.getPassword());
		}
		return Redisson.create(config);
	}

	@Bean
	public DistributedLocker distributedLocker(RedissonClient redissonClient) {
		RedissonLocker locker = new RedissonLocker();
		locker.setRedissonClient(redissonClient);
		return locker;
	}
	
	@Bean
	public DistributedObject distributedObject(RedissonClient redissonClient) {
		DistributedObject locker = new DistributedObject();
		locker.setRedissonClient(redissonClient);
		return locker;
	}

}
